/*******************************************************************************
 * Copyright (c) 2011 TXT e-solutions SpA
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 *
 * Authors:
 *     Cristoforo Seccia (TXT e-solutions SpA)
 *
 * Contributors:
 *      Domenico Rotondi (TXT e-solutions SpA)
 *******************************************************************************/
package it.txt.access.capability.demo.client.impl;

import it.txt.access.capability.commons.schema.validation.CapabilitySchemaValidationHandlerException;
import it.txt.access.capability.commons.signer.X509DocumentSigner;
import it.txt.access.capability.commons.signer.model.X509CertificateKeyValues;
import it.txt.access.capability.demo.client.model.CapabilityAuthDemoClientModel;
import it.txt.access.capability.demo.client.model.CapabilityAuthDemoServiceModel;
import it.txt.access.capability.demo.schema.CapabilityRequestType;
import it.txt.access.capability.demo.schema.CapabilityResponseType;
import it.txt.access.capability.demo.schema.factory.CapabilityDemoFactoryException;
import it.txt.access.capability.demo.schema.request.factory.CapabilityDemoRequestFactory;
import it.txt.access.capability.demo.schema.response.factory.CapabilityDemoResponseFactory;
import it.txt.access.capability.factory.CapabilitySchemaFactory;
import it.txt.access.capability.factory.CapabilitySchemaFactoryException;
import it.txt.access.capability.schema.AccessRightsCapabilityType;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;

/**
 *
 * @author Cristoforo Seccia (TXT e-solutions SpA)
 */
public class CapabilityAuthDemoClientImpl {

    private static final Logger LOGGER = Logger.getLogger(CapabilityAuthDemoClientImpl.class.getName());
    private CapabilityAuthDemoClientModel authDemoClientModel;
    private X509CertificateKeyValues certificateKeyValues;
    private AccessRightsCapabilityType capability;

    public CapabilityAuthDemoClientImpl(CapabilityAuthDemoClientModel model)
            throws CapabilityAuthDemoClientException {
        authDemoClientModel = model;
        try {
            CapabilitySchemaFactory.getInstance(authDemoClientModel.getCapabilitySchemasPath());
            CapabilityDemoRequestFactory.getInstance(authDemoClientModel.getCapabilitySchemasPath());
            CapabilityDemoResponseFactory.getInstance(authDemoClientModel.getCapabilitySchemasPath());
            certificateKeyValues = X509DocumentSigner.getCertificateKeyValues(
                    authDemoClientModel.getX509DocumentSignerInfo());
            LOGGER.log(Level.INFO, "Capability Auth Demo ServiceKeystore Data - "
                    + "Using Server ID: " + "{0}",
                    authDemoClientModel.getX509DocumentSignerInfo().getSignerID());
        } catch (CapabilityDemoFactoryException e) {
            throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        } catch (CapabilitySchemaFactoryException e) {
            throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        } catch (GeneralSecurityException e) {
            throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        }

    }

    public CapabilityRequestType getNewCapabilityRequestClient() throws CapabilityAuthDemoClientException {
        try {
            LOGGER.log(Level.INFO, "Creating new Capability Auth Demo Request...");
            File capabilityFile = new File(authDemoClientModel.getCapabilityPath());
            capability = CapabilitySchemaFactory.getInstance().createAccessRights(capabilityFile);
            CapabilityRequestType requestType = CapabilityDemoRequestFactory.getInstance().createRequest(
                    authDemoClientModel.getOperationID(), authDemoClientModel.getResourceID(), capability);
            Document requestDoc =
                    CapabilityDemoRequestFactory.getInstance().createRequestDocument(requestType);
            X509DocumentSigner.signXMLElement(requestDoc.getDocumentElement(), certificateKeyValues,
                    CapabilityDemoRequestFactory.SIGN_DOCUMENT_AFTER_NODE);
            CapabilityRequestType crt = CapabilityDemoRequestFactory.getInstance().createRequest(new DOMSource(requestDoc));
            LOGGER.log(Level.INFO, "Capability Auth Demo Request CREATED!");
            return crt;
        }
        catch (CapabilityDemoFactoryException e) {
            throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        }
        catch (CapabilitySchemaFactoryException e) {
            throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        }
         catch (CapabilitySchemaValidationHandlerException e) {
             throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        }
        catch (GeneralSecurityException e) {
            throw new CapabilityAuthDemoClientException(e.getMessage(), e);
        }
    }

    public void checkCapabilityAuthResponse(CapabilityResponseType crt) throws CapabilityAuthDemoClientException {
        //Request received now get the cabaility request and make controls.
        CapabilityAuthDemoServiceModel demoServiceModel = null;
        LOGGER.log(Level.INFO, "recoverin capability auth service response");
        demoServiceModel = CapabilityAuthDemoClientHelper.recoverServiceResponseInfo(crt);
        //Recover the request ID.        
        LOGGER.log(Level.INFO, "Capability Auth Demo Service - Response ID: {0}",
                demoServiceModel.getResponseID());
        LOGGER.log(Level.INFO, "Capability Auth Demo Service - Response Status: {0}",
                demoServiceModel.getServiceResponseStatus());
        LOGGER.log(Level.INFO, "Capability Auth Demo Service - Response Signer: {0}",
                demoServiceModel.getResponseSigner());
        LOGGER.log(Level.INFO, "Capability Auth Demo Service - Response Signer Key ID: {0}",
                demoServiceModel.getSignerKeyID());
        LOGGER.log(Level.INFO, "Capability Auth Demo Service - Response Signer Key Issuer: {0}",
                demoServiceModel.getSignerKeyIssuer());
    }
}
